package com.hfy.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hfy.admin.mapper.*;
import com.hfy.admin.service.ApplyService;
import com.hfy.feign.IMusicClient;
import com.hfy.model.Bo.AlbumBo;
import com.hfy.model.dto.admin.ApplyMusicDto;
import com.hfy.model.dto.admin.ApplyMusicListDto;
import com.hfy.model.dto.admin.ApplyMusicianDto;
import com.hfy.model.po.admin.AdminPo;
import com.hfy.model.po.admin.ApplyAlbumPo;
import com.hfy.model.po.admin.ApplyMusicPo;
import com.hfy.model.po.admin.ApprovalLogAlbumPo;
import com.hfy.model.vo.admin.ApplyAlbumVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import result.Result;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * @ author 韩
 * time: 2024/7/14 23:09
 */
@Service
public class ApplyServiceImpl implements ApplyService {

    // 还未审批
    private final int APPLY_STATUS_BEFORE = 0;
    private final int APPLY_STATUS_ALLOW = 1;
    private final int APPLY_STATUS_PASS = 2;
    @Autowired
    private ApplyMapper applyMapper;
    @Autowired
    private ApplyMusicianMapper applyMusicianMapper;
    @Autowired
    private DraftMapper draftMapper;

    @Autowired
    private ApplyAlbumMapper applyAlbumMapper;

    @Autowired
    private ApplyMusicMapper applyMusicMapper;

    @Autowired
    private IMusicClient musicClient;

    @Autowired
    private ApprovalLogAlbumMapper approvalLogAlbumMapper;

    @Autowired
    private AdminMapper adminMapper;


    @Override
    public Result applyMusician(ApplyMusicianDto dto) {
        // 1. 第一部当然就是校验参数
        boolean isEmpty = BeanUtil.isEmpty(dto);
        if (isEmpty) return Result.error("参数不能为空");
        // 然后就是详细的校验 比如名字长度必须1-15等等
        if (dto.getName().length() < 1 || dto.getName().length() >15) return Result.error("名字长度必须在1-15之间");
        if (dto.getBrief().length() < 10 || dto.getBrief().length() > 1000) return Result.error("简介长度必须在10-1000之间");

        // 2. 然后向数据库里插入一条申请信息
        applyMusicianMapper.insertApplyMusicianRecord(dto);

        return Result.ok();
    }

    @Override
    public Result applyMusicianIsOk(Long account) {
        // 先校验参数
        if (account == null) return Result.error("账号不能为空！");
        // 然后进行状态分析，去查库
        // 当查到 0 即为还没有审核
        // 当查到 1 即为审核已经通过
        // 使用懒汉式 当查到的状态为 2 即为审核未通过 删掉这条记录即可或者加一个逻辑删除字段
        // 返回三个数字 0是还没有审核 显示等待审核 1是通过 直接换到上传音乐页面 2是未通过 还是申请页面
        int status = applyMusicianMapper.queryApplyStatus(account);
        if (status == 0) {
            return Result.ok(0);
        } else if (status == 1) {
            return Result.ok(1);
        } else if (status == 2) {
            applyMusicianMapper.deleteByLogic(account);
            return Result.ok(2);
        } else {
            return Result.error("出现了不应该出现的状态");
        }
    }

    @Override
    @Transactional
    public Result applyMusic(ApplyMusicListDto dto) {
        // 向数据库里开始插入信息，先校验参数
        boolean isEmpty = BeanUtil.isEmpty(dto);
        if (isEmpty) return Result.error("参数不许为空！");
        // 有两个表 所以分两个表进行插入
        try {
            List<ApplyMusicDto> musicList = dto.getMusicList();
            ApplyAlbumPo applyAlbumPo = new ApplyAlbumPo();
            applyAlbumPo.setAlbumId(dto.getAlbumId());
            applyAlbumPo.setMusicCount(musicList.size());
            applyAlbumPo.setApplyTime(LocalDateTime.now());
            applyAlbumMapper.insert(applyAlbumPo);

            applyMapper.insertAlbumMusic(applyAlbumPo.getId(), musicList);
        } catch (Exception e) {
            return Result.error("一个专辑内的歌曲不能重名");
        }

        // 因为已经提交 还要删除草稿箱的 数据，其实草稿箱使用redis实现更好 但是无所谓了
        draftMapper.delDraftMusicList(dto.getAccount());
        return Result.ok();
    }

    @Override
    public Result getApplyAlbumInfoById(Integer id) {
        if (id == null) return Result.error("G了");

        ApplyAlbumPo applyAlbumPo = applyAlbumMapper.selectById(id);
        // Po 转 Vo

        ApplyAlbumVo applyAlbumVo = BeanUtil.copyProperties(applyAlbumPo, ApplyAlbumVo.class);
        // 获取专辑id的列表
        List<Integer> idList = Collections.singletonList(applyAlbumVo.getAlbumId());
        // 查询到对应专辑的信息
        List<AlbumBo> albumBos = musicClient.pageAlbumByIdList(idList);
        BeanUtil.copyProperties(albumBos.get(0), applyAlbumVo);

        LambdaQueryWrapper<ApprovalLogAlbumPo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ApprovalLogAlbumPo::getApplyAlbumId, id);
        ApprovalLogAlbumPo approvalLogAlbumPo = approvalLogAlbumMapper.selectOne(queryWrapper);
        if (approvalLogAlbumPo != null) {
            // 如果有处理记录
            AdminPo adminPo = adminMapper.selectById(approvalLogAlbumPo.getAdminId());
            applyAlbumVo.setApplyDes(approvalLogAlbumPo.getDes());
            applyAlbumVo.setAdminEmail(adminPo.getEmail());
        }

        List<ApplyMusicPo> applyMusicList = applyMusicMapper.selectApplyMusicVoList(id);

        for (ApplyMusicPo item : applyMusicList) {
            if (item.getDuration() != null) {
                int temp = Integer.parseInt(item.getDuration());
                int minutes = temp / 60;
                int seconds = temp % 60;
                // 使用String.format来格式化分钟和秒数，确保它们都是两位数
                item.setDuration(String.format("%02d:%02d", minutes, seconds));
            }
        }
        applyAlbumVo.setMusicList(applyMusicList);

        return Result.ok(applyAlbumVo);
    }
}
